package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Redis ID服务
 * 用于生成不重复的递增ID
 */
@Service
public class RedisIdService {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    // Redis key前缀
    private static final String CUSTOMER_ID_KEY = "customer:id:counter";
    private static final String ORDER_ID_KEY = "order:id:counter";
    
    /**
     * 生成下一个客户ID
     * @return 客户ID
     */
//    public Long generateNextCustomerId() {
//        return redisTemplate.opsForValue().increment(CUSTOMER_ID_KEY);
//    }
    private static final int BATCH_SIZE = 1000;
    private volatile long currentId = 0;
    private volatile long remainingIds = 0;

    public synchronized long generateNextCustomerId() {
        if (remainingIds <= 0) {
            // 从 Redis 获取下一批 ID
            Long nextBatchStart = redisTemplate.opsForValue().increment("customer_id_batch", BATCH_SIZE);
            currentId = nextBatchStart;
            remainingIds = BATCH_SIZE;
        }
        return currentId++;
    }
    
    /**
     * 生成下一个订单ID
     * @return 订单ID
     */
    public Long generateNextOrderId() {
        return redisTemplate.opsForValue().increment(ORDER_ID_KEY);
    }
    
    /**
     * 获取当前客户ID计数器值
     * @return 当前客户ID值
     */
    public Long getCurrentCustomerId() {
        String value = redisTemplate.opsForValue().get(CUSTOMER_ID_KEY);
        return value != null ? Long.parseLong(value) : 0L;
    }
    
    /**
     * 获取当前订单ID计数器值
     * @return 当前订单ID值
     */
    public Long getCurrentOrderId() {
        String value = redisTemplate.opsForValue().get(ORDER_ID_KEY);
        return value != null ? Long.parseLong(value) : 0L;
    }
    
    /**
     * 重置客户ID计数器
     * @param startValue 起始值
     */
    public void resetCustomerIdCounter(Long startValue) {
        redisTemplate.opsForValue().set(CUSTOMER_ID_KEY, String.valueOf(startValue));
    }
    
    /**
     * 重置订单ID计数器
     * @param startValue 起始值
     */
    public void resetOrderIdCounter(Long startValue) {
        redisTemplate.opsForValue().set(ORDER_ID_KEY, String.valueOf(startValue));
    }
    
    /**
     * 批量生成客户ID
     * @param count 生成数量
     * @return 起始ID
     */
    public Long generateBatchCustomerIds(int count) {
        return redisTemplate.opsForValue().increment(CUSTOMER_ID_KEY, count) - count + 1;
    }
    
    /**
     * 批量生成订单ID
     * @param count 生成数量
     * @return 起始ID
     */
    public Long generateBatchOrderIds(int count) {
        return redisTemplate.opsForValue().increment(ORDER_ID_KEY, count) - count + 1;
    }
}






